#include "ImageView.h"
#include <QResizeEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QMutexLocker>

#include "../Utility/XXlogger.h"
#include <QFileInfo>
#include <QLabel>
#include <QCoreApplication>
#include <QApplication>

#include <QDesktopWidget>

ImageView::ImageView(QWidget *parent)
    : QWidget(parent){
    setAttribute(Qt::WA_StyledBackground);
    connect(&_imageThread,SIGNAL(sigFinsihed(QPixmap)),this,SLOT(imageThread_onFinished(QPixmap)),Qt::QueuedConnection);
    _borderWidth = 0;
    _previewEnabled = false;
    _scrollArea = nullptr;
}
ImageView::~ImageView(){
    if(_imageThread.isRunning()){
        _imageThread.requestInterruption();
        _imageThread.wait();
    }
}

void ImageView::reset(const QString &path, bool keepSize){
    _path = path;
    _keepSize = keepSize;
    if(keepSize){
        _imageThread.start(path, QSize());
    }
    else{
        QSize size = this->size();
        //xxLogStr(QString("path%1 size:%2*%3").arg(path).arg(size.width()).arg(size.height()));
        size.setWidth(size.width()-_borderWidth*2);
        size.setHeight(size.height()-_borderWidth*2);
        _imageThread.start(path, size);
    }
}

void ImageView::resizeEvent(QResizeEvent *event){
    QWidget::resizeEvent(event);
    if(!_keepSize && !_path.isEmpty()){
        QSize size = this->size();
        size.setWidth(size.width()-_borderWidth*2);
        size.setHeight(size.height()-_borderWidth*2);
        _imageThread.start(_path,size);
    }
}
void ImageView::paintEvent(QPaintEvent *event){
    QWidget::paintEvent(event);
    if(_path.isEmpty() || _pixmap.isNull()){
        return;
    }

    QSize targetSize = this->size();
    qreal x, y;
    if(_pixmap.devicePixelRatio()>1){
        x = (targetSize.width() - _pixmap.width()/_pixmap.devicePixelRatio() -_borderWidth*2) * 0.5;
        y = (targetSize.height() - _pixmap.height()/_pixmap.devicePixelRatio()-_borderWidth*2) * 0.5;
    }
    else{
        x = (targetSize.width() - _pixmap.width()-_borderWidth*2) * 0.5;
        y = (targetSize.height() - _pixmap.height()-_borderWidth*2) * 0.5;
    }

    QPainter painter(this);
    painter.drawPixmap(QPointF(x+_borderWidth,y+_borderWidth),_pixmap);
}
void ImageView::mouseDoubleClickEvent(QMouseEvent *event){
    if(!_previewEnabled){
        QWidget::mouseDoubleClickEvent(event);
        return;
    }

    static const int width = 600;
    int height = QApplication::desktop()->availableGeometry().size().height()-50-QApplication::desktop()->availableGeometry().y();

    QPixmap pixmap(_path);
    if(pixmap.isNull()){
        pixmap = QPixmap(_path,"jpg");
    }
    pixmap = pixmap.scaledToWidth(width,Qt::SmoothTransformation);
    if(pixmap.height()<height){
        height = pixmap.height();
    }

    QLabel *label = new QLabel;
    label->setFixedWidth(width);
    label->setFixedSize(pixmap.size());
    label->setPixmap(pixmap);

    if(nullptr != _scrollArea){
        _scrollArea->deleteLater();
    }
    _scrollArea = new QScrollArea(this);
    _scrollArea->setWindowFlags(Qt::Window);
    _scrollArea->setAttribute(Qt::WA_DeleteOnClose);
    _scrollArea->setWidget(label);
    _scrollArea->setFixedWidth(width);
    _scrollArea->setWindowTitle(QFileInfo(_path).fileName());
    _scrollArea->setGeometry(0,0,width,height);
    _scrollArea->setStyleSheet("background:white;");
    _scrollArea->show();
    connect(_scrollArea,&QScrollArea::destroyed,this,[&](QObject *obj){
        if(obj == _scrollArea){
            _scrollArea = nullptr;
        }
    });
}

void ImageView::imageThread_onFinished(QPixmap pixmap){
    _pixmap = pixmap;
    if(_keepSize){
        this->setFixedSize(_pixmap.size());
    }
    repaint();
}

void ImageThread::start(const QString &path, QSize size){
    if(QThread::isRunning()){
        //xxLogStr(QString("next path:%1 size:%2*%3").arg(_path).arg(_size.width()).arg(_size.height()));
        setNext(path,size);
        return;
    }
    _path = path;
    _size = size;
    _hasNext = false;
    //xxLogStr(QString("path:%1 size:%2*%3").arg(_path).arg(_size.width()).arg(_size.height()));
    QThread::start();
}
void ImageThread::run(){
    QPixmap pixmap;
    do{
        //xxLogStr(QString("\n"
        //                 "\tpath:%1\n"
        //                 "\tsize:%2*%3").arg(_path).arg(_size.width()).arg(_size.height()));
        QPixmap srcPixmap(_path);
        if(srcPixmap.isNull()){
            srcPixmap = QPixmap(_path,"jpg");
        }
        if(!_size.isNull()){
            pixmap = srcPixmap.scaled(_size,Qt::KeepAspectRatio,Qt::SmoothTransformation);
        }
        else{
            pixmap = srcPixmap;
        }
        //xxLogStr(QString("\n"
        //                 "\tpixmap path:%1\n"
        //                 "\tsize:%2*%3").arg(_path).arg(pixmap.width()).arg(pixmap.height()));
        if(isInterruptionRequested()){
            return;
        }
    }while(turnToNext());
    emit sigFinsihed(pixmap);
}
